﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text;

using Wicresoft.Framework.Organization;
using Wicresoft.Busi.BizLogic;

using Wicresoft.Common;
using System.Web.UI.DataVisualization.Charting;

public partial class NewMeetingRoom_StatisticList : BaseAuthenticationPage
{
    public string SearchDefaultText
    {
        get
        {
            return "搜索 月份";
        }
    }

    public string SearchClause
    {
        get
        {
            if (ViewState["SearchClause"] == null)
                ViewState["SearchClause"] = "1=1 and StatusCN='" + Enum.ApplyStatusEnum.审核通过.ToString() + "' and AuditTime>='" + DateTime.Now.ToString("yyyy-MM-01") + "' and AuditTime<'" + DateTime.Now.AddMonths(1).ToString("yyyy-MM-01") + "'";
            return ViewState["SearchClause"].ToString();
        }
        set
        {
            ViewState["SearchClause"] = value;
        }
    }

    protected DataTable DTData
    {
        get
        {
            if (ViewState["DTData"] == null)
                ViewState["DTData"] = new DataTable();
            return ViewState["DTData"] as DataTable;
        }
        set
        {
            ViewState["DTData"] = value;
        }
    }

    protected DataTable DTAllData
    {
        get
        {
            if (ViewState["DTAllData"] == null)
                ViewState["DTAllData"] = new DataTable();
            return ViewState["DTAllData"] as DataTable;
        }
        set
        {
            ViewState["DTAllData"] = value;
        }
    }


    protected void Page_Load(object sender, System.EventArgs e)
    {
        this.ShowLRLayoutButton = false;
        this.ShowUDLayoutButton = false;
        this.ShowSimpleLayoutButton = false;
        this.DefaultLayout = LayoutCode.Simple.ToString();

        this.tbSearch.Attributes.Add("onfocus", string.Format("clearText(this, '{0}');", SearchDefaultText) + "WdatePicker({dateFmt:'yyyy-MM'});");
        this.tbSearch.Attributes.Add("onblur", string.Format("insertText(this, '{0}');", SearchDefaultText));
        this.tbSearch.Attributes.Add("onkeydown", "return searchClick();");
        this.Title = "申请统计列表";
      

        if (!IsPostBack)
        {
            tbSearch.Text = SearchDefaultText;

            this.Order.OrderColumn = "AuditTime";//vwMeetingRoomApply.SQLCOL_APPLYDATE ;
            this.Order.OrderDirection = "DESC";
            BindData();

            DTAllData = DataAccess.Select(typeof(Wicresoft.JDPostBoard.Entity.vwMeetingRoomApply), SearchClause);
            BindChart(DTAllData);
        }
    }

    protected void BindChart(DataTable dt)
    {
        // Add series to the chart

        //if (Chart1.Series.FindByName("My series") != null)
        //    Chart1.Series.RemoveAt(0);
        Hashtable ht = new Hashtable();
        if (dt != null)
        {
            foreach (DataRow dr in dt.Rows)
            {
                if (ht[dr["Sbbm"].ToString()] == null)
                    ht[dr["Sbbm"].ToString()] = 1;
                else
                    ht[dr["Sbbm"].ToString()] = int.Parse(ht[dr["Sbbm"].ToString()].ToString()) + 1;
            }
        }

        //Series series = Chart1.Series.Add("My series");
        Series series = Chart1.Series["总次数"];
        // Set series visual attributes
        series.ChartType = SeriesChartType.Column;

        series.ShadowOffset = 1;
        series.Font = new Font("Times New Format", 7f);
        series.BorderColor = Color.DarkGray;
        //series.CustomAttributes = "LabelStyle=Outside";

        // Set series and legend tooltips
        series.ToolTip = "#LEGENDTEXT的总次数: #VAL";
        series.LegendToolTip = "#PERCENT";
        series.PostBackValue = "#INDEX";
        series.LegendPostBackValue = "#INDEX";
        Chart1.Titles[0].Text = "部门会议室申请分布图";

        //3D
        //Chart1.ChartAreas["ChartArea1"].Area3DStyle.Enable3D = true;

        // Populate series data
        double[] yValues = new double[ht.Count]; //{ 65.62, 75.54, 60.45, 34.73, 85.42, 32.12, 55.18, 67.15, 56.24, 23.65 };
        string[] xValues = new string[ht.Count];//{ "France", "Canada", "Germany", "USA", "Italy", "Russia", "China", "Japan", "Sweden", "Spain" };
        int Index = 0;
        foreach (DictionaryEntry de in ht)
        {
            yValues[Index] = double.Parse(de.Value.ToString());
            xValues[Index] = de.Key.ToString();
            Index++;
        }
        series.Points.DataBindY(yValues);

        for (int pointIndex = 0; pointIndex < series.Points.Count; pointIndex++)
        {
            series.Points[pointIndex].LegendText = xValues[pointIndex];
            series.Points[pointIndex].AxisLabel = xValues[pointIndex];
        }

        //if (!this.IsPostBack)
        //{
        //    if (series.Points.Count > 0)
        //        series.Points[0].CustomProperties += "Exploded=true";
        //}
    }

    protected void Chart1_Click(object sender, ImageMapEventArgs e)
    {

        BindChart(DTAllData);
        int pointIndex = int.Parse(e.PostBackValue);
        Series series = Chart1.Series["总次数"];
        if (pointIndex >= 0 && pointIndex < series.Points.Count)
        {
            series.Points[pointIndex].CustomProperties += "Exploded=true";
            BindData(series.Points[pointIndex].LegendText);
        }
    }

    protected void Page_PreRender(object sender, EventArgs e)
    {


    }



    protected override void Pager_PageChanged(object sender, EventArgs e)
    {
        BindData();
        DTAllData = DataAccess.Select(typeof(Wicresoft.JDPostBoard.Entity.vwMeetingRoomApply), SearchClause);
        BindChart(DTAllData);
        base.Pager_PageChanged(sender, e);
    }

    protected override void Order_OrderChanged(object sender, EventArgs e)
    {
        BindData();
        DTAllData = DataAccess.Select(typeof(Wicresoft.JDPostBoard.Entity.vwMeetingRoomApply), SearchClause);
        BindChart(DTAllData);
        base.Order_OrderChanged(sender, e);
    }

    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        BindData();
        DTAllData = DataAccess.Select(typeof(Wicresoft.JDPostBoard.Entity.vwMeetingRoomApply), SearchClause);
        BindChart(DTAllData);
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        SearchClause = "StatusCN='" + Enum.ApplyStatusEnum.审核通过.ToString() + "'";
        if (tbSearch.Text != string.Empty && tbSearch.Text != SearchDefaultText)
            SearchClause += string.Format(" AND AuditTime>='{0}' and AuditTime<'{1}'", this.tbSearch.Text + "-01", Convert.ToDateTime(this.tbSearch.Text + "-01").AddMonths(1).ToString("yyyy-MM-01"));

        //Pager.ResetPager();
        BindData();
        DTAllData = DataAccess.Select(typeof(Wicresoft.JDPostBoard.Entity.vwMeetingRoomApply), SearchClause);
        BindChart(DTAllData);
    }

    protected void btnAdvancedSearch_Click(object sender, EventArgs e)
    {
        SearchClause = "StatusCN='" + Enum.ApplyStatusEnum.审核通过.ToString() + "'";

        if (this.tbStartTime.Text != "" && this.tbEndTime.Text != "")
        {
            if (Convert.ToDateTime(this.tbStartTime.Text + "-01") > Convert.ToDateTime(this.tbEndTime.Text + "-01"))
            {
                Response.Write("<script>alert('开始月份不能小于结束月份');</script>");
                return;
            }
            SearchClause += string.Format(" AND {0} >= '{1}' AND {0} < '{2}'", Wicresoft.JDPostBoard.Entity.vwMeetingRoomApply.SQLCOL_AUDITTIME, this.tbStartTime.Text + "-01", Convert.ToDateTime(this.tbEndTime.Text + "-01").AddMonths(1).ToString("yyyy-MM-01"));

        }
        else if (this.tbStartTime.Text != "")
            SearchClause += string.Format(" AND {0} >= '{1}'", Wicresoft.JDPostBoard.Entity.vwMeetingRoomApply.SQLCOL_AUDITTIME, this.tbStartTime.Text + "-01");
        else if (this.tbEndTime.Text != "")
            SearchClause += string.Format(" AND {0} < '{1}'", Wicresoft.JDPostBoard.Entity.vwMeetingRoomApply.SQLCOL_AUDITTIME, Convert.ToDateTime(this.tbEndTime.Text + "-01").AddMonths(1).ToString("yyyy-MM-01"));

        //Pager.ResetPager();
        BindData();
        DTAllData = DataAccess.Select(typeof(Wicresoft.JDPostBoard.Entity.vwMeetingRoomApply), SearchClause);
        BindChart(DTAllData);
    }

    private void BindData()
    {
        Wicresoft.Common.PagingEntity pe = new PagingEntity();
        pe.PageIndex = this.Pager.PageIndex;
        pe.PageSize = this.Pager.PageSize;
        pe.TableName = "vwMeetingRoomApply";
        pe.SelectString = "*";
        if (this.Order.OrderDirection.ToLower().Contains("desc"))
        {
            pe.DescString = this.Order.OrderColumn + " DESC";
            pe.AscString = this.Order.OrderColumn + " ASC";
        }
        else
        {
            pe.DescString = this.Order.OrderColumn + " ASC";
            pe.AscString = this.Order.OrderColumn + " DESC";
        }

        //DataTable dt = BLMeetingRoomApply.GetUnAuditMeetingRoomApply(CurrentUser.Name, pe);
        //string whereClause = " Status='" + MeetingStatus.AUDIT + "'";

        //if (this.tbSearch.Text.Trim() != "" && tbSearch.Text != SearchDefaultText)
        //    whereClause += " AND (Topic like '%" + this.tbSearch.Text.Trim().Replace("'", "").Replace("%", "[%]") + "%' or RoomName like '%" + this.tbSearch.Text.Trim().Replace("'", "").Replace("%", "[%]") + "%')";

        //if (this.txtDateFrom.Text.Trim() != "")
        //    whereClause += " AND ApplyDate >='" + this.txtDateFrom.Text.Trim() + "' AND ApplyDate<'" + Convert.ToDateTime(this.txtDateFrom.Text.Trim()).AddDays(1) + "' ";

        //if (this.txtDateTo.Text.Trim() != "")
        //    whereClause += " AND MeetingDate >='" + this.txtDateTo.Text.Trim() + "' AND MeetingDate<'" + Convert.ToDateTime(this.txtDateTo.Text.Trim()).AddDays(1) + "' ";

        DataTable dt = DataAccess.Select(typeof(Wicresoft.JDPostBoard.Entity.vwMeetingRoomApply),SearchClause);

        foreach (DataRow dr in dt.Rows)
        {
            if (dr[Wicresoft.Busi.Entity.MeetingRoomApply.SQLCOL_TOPIC].ToString().Length > 100)
                dr[Wicresoft.Busi.Entity.MeetingRoomApply.SQLCOL_TOPIC] = dr[Wicresoft.Busi.Entity.MeetingRoomApply.SQLCOL_TOPIC].ToString().Substring(0, 26) + "...";
        }

        Pager.RecordCount = pe.RecordCount;
        DTData = dt;
        rptOrder.DataSource = dt;
        rptOrder.DataBind();
    }

    private void BindData(string Department)
    {
        int recordCount = 0;
        string orderString = this.Order.OrderDirection == "DESC" ? string.Format("{0} {1},{2}", this.Order.OrderColumn, this.Order.OrderDirection, Wicresoft.JDPostBoard.Entity.vwMeetingRoomApply.SQLCOL_ID) : this.Order.OrderColumn;
        DTData = DataAccess.Select(typeof(Wicresoft.JDPostBoard.Entity.vwMeetingRoomApply), Pager.PageIndex, Pager.PageSize, SearchClause + " And Sbbm='" + Department + "'", orderString, ref recordCount);
        Pager.RecordCount = recordCount;
        rptOrder.DataSource = DTData;
        rptOrder.DataBind();

    }

    protected void rptProduct_ItemCommand(object source, RepeaterCommandEventArgs e)
    {

    }

    protected void Print_Click(object sender, EventArgs e)
    {
        if (DTData == null || DTData.Rows.Count == 0)
        {
            WebCommon.ShowMessage(this, "无数据");
            return;
        }
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "GB2312";
        Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("会议室使用统计报表") + ".xls");
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        Response.ContentType = "application/ms-excel";
        string body = ToExcel();
        Response.Write(body);
        Response.End();
    }

    public string ToExcel()
    {
        int month = DateTime.Now.Month;

        string displayTime = WebCommon.MonthIntToChinise(month);

        string ExcelHeader = "<div   style=\"text-align:center; background-color: #006699;font-size: 15pt;color: #000000;padding: 2pt;width:100%\">会议室使用统计报表<br/>(" + displayTime + ")</div>";

        DataTable dtRoomList = DataAccess.Select(typeof(Wicresoft.JDPostBoard.Entity.MeetingRooms), "");
        Hashtable ht = new Hashtable();
        int index = 1;
        foreach (DataRow dr in dtRoomList.Rows)
        {
            if (!ht.ContainsValue(dr["RoomName"].ToString() + "|" + dr["ID"].ToString()))
            {
                ht.Add(index, dr["RoomName"].ToString() + "|" + dr["ID"].ToString());
                index++;
            }
        }

        Hashtable htDepart = new Hashtable();
        index = 1;
        foreach (DataRow dr in DTData.Rows)
        {
            if (!htDepart.ContainsValue(dr["Sbbm"].ToString()))
            {
                htDepart.Add(index, dr["Sbbm"].ToString());
                index++;
            }
        }

        string TableHeader = "<table border='1' style='width:100%;'><tr><th></th>";
        for (int i = 0; i < ht.Count; i++)
        {
            TableHeader += "<th>" + ht[i + 1].ToString().Split('|')[0] + "</th>";

        }
        TableHeader += "</tr>";



        string TableBody = "";

        for (int i = 0; i < htDepart.Count; i++)
        {
            TableBody += "<tr><td style='text-align:center;'>" + htDepart[i + 1].ToString() + "</td>";

            float PriceSum = 0;
            for (int k = 0; k < ht.Count; k++)
            {
                DataRow[] drSelect = DTData.Select("Sbbm='" + htDepart[i + 1].ToString() + "' and RoomID='" + ht[k + 1].ToString().Split('|')[1] + "'");

                TableBody += "<td>" + drSelect.Length.ToString() + "</td>";
            }
            TableBody += "</tr>";
        }


        string TableFooter = "</table>";

        return ExcelHeader + TableHeader + TableBody + TableFooter;

    }

}
